package com.yxq.mdt.app.base;

import android.os.Bundle;

import androidx.annotation.Nullable;

import com.yxq.mdt.app.base.ibase.IBaseContract;

/**
 * 用于在viewpager中的fragment延迟加载数据，避免一次加载过多的数据，导致卡顿或奔溃
 */
public abstract class LazyLoadFragment<P extends IBaseContract.IBasePresenter> extends BaseFragment<P> {
    /**
     * 是否初始化过布局
     */
    protected boolean isViewInitiated;
    /**
     * 当前界面是否可见
     */
    protected boolean isVisibleToUser;
    /**
     * 是否加载过数据
     */
    protected boolean isDataInitiated;

    public abstract void onLoadData(int pageIndex);

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        isViewInitiated = true;
        prepareFetchData();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.isVisibleToUser = isVisibleToUser;
        if (isVisibleToUser) {
            prepareFetchData();
        }
    }

    public void prepareFetchData() {
        prepareFetchData(false);
    }

    /**
     * 判断懒加载条件
     *
     * @param forceUpdate 强制更新，好像没什么用？
     */
    public void prepareFetchData(boolean forceUpdate) {
        if (isVisibleToUser && isViewInitiated && (!isDataInitiated || forceUpdate)) {
            isDataInitiated = true;
            onLoadData(1);
        }
    }

    public void loadData() {

    }
}
